package com.hhq.controller;

import com.hhq.entity.Dept;
import com.hhq.entity.Employee;
import com.hhq.entity.Statistics;
import com.hhq.entity.User;
import com.hhq.service.Deptservice;
import com.hhq.service.Employeeservice;
import com.hhq.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private Userservice userservice;
    @Autowired
    private Deptservice deptservice;
    @Autowired
    private Employeeservice employeeservice;

    @RequestMapping("/tologin")
    public String tologin(){
        return "loginForm";
    }

    @RequestMapping("/checkLogin")
    public String checkLogin(User user, HttpSession session, HttpServletRequest request,String loginname,String password){
        Statistics statistics = new Statistics();

        List<User> listuser = userservice.getAllUser();
        statistics.setUsernum(listuser.size());
        System.out.println(statistics.getUsernum());


        List<Dept> listdept = deptservice.getAllDept();
        statistics.setDeptnum(listdept.size());
        System.out.println(statistics.getDeptnum());

        List<Employee> listemployee = employeeservice.getAllEmployee();
        statistics.setEmployeenum(listemployee.size());
        System.out.println(statistics.getEmployeenum());

        session.setAttribute("statistics",statistics);

        List<User> list= userservice.findUserByName(loginname);
        User user1 = list.get(0);
        session.setAttribute("user1",user1);

        System.out.println(user);
        boolean t = userservice.checkAdminLogin(loginname,password);
        System.out.println(t);
        if(t){
            session.setAttribute("user",user);
            return "index";
        }else{
            request.setAttribute("message","账号或密码错误，请重新输入！");
            return "forward:tologin";
        }
    }
    @RequestMapping("/toSign")
    public  String toSign(){
        return "sign-up";
    }

    @RequestMapping("sign-up")
    public  String sign_up(User user,HttpSession session, HttpServletRequest request){
        List<User> users = userservice.findUserByName(user.getLoginname());
        if (users.size()!=0){
            request.setAttribute("message","登陆名已使用，请换一个登录名！");
            return "forward:toSign";
        }else {
            int i = userservice.addUser(user);
            request.setAttribute("message","注册成功，请登陆...");
        }

        return "forward:tologin";
    }

    @RequestMapping("/LogOut")
    public String LogOut(HttpSession session){
        return "forward:tologin";
    }

}
